package com.gxa.uhome.controller;

import com.alibaba.fastjson.JSON;
import com.gxa.uhome.exception.BusinessException;
import com.gxa.uhome.pojo.Order;
import com.gxa.uhome.pojo.vo.UODSVo;
import com.gxa.uhome.pojo.User;
import com.gxa.uhome.pojo.UserAddress;
import com.gxa.uhome.service.OrderService;
import com.gxa.uhome.service.UODSVoService;
import com.gxa.uhome.service.UserAddressService;
import com.gxa.uhome.service.UserService;
import com.gxa.uhome.util.AliMsm;
import com.gxa.uhome.util.ExcelUtil;
import com.gxa.uhome.util.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * User: Sanruy Mu
 * Date: 2021/06/07 13:26
 * Description:
 * Version: V1.0
 */
@CrossOrigin
@RestController
@RequestMapping(value = "/user", method = RequestMethod.POST)
@Api(tags = "User用户管理模块", produces = "application/json;charset=UTF-8")
public class UserController {
    @Resource
    UserService userService;
    @Resource
    UODSVoService uodsVoService;
    @Resource
    OrderService orderService;
    @Resource
    UserAddressService userAddressService;


    @ApiOperation(value = "统计用户数量")
    @PostMapping("/selectAll")
    public JsonResult selectAll() {
        JsonResult jsonResult = new JsonResult();
        try {
            List<User> users = userService.selectUser();
            int size = users.size();
            jsonResult.setCode("1");
            jsonResult.setData(size);
        } catch (BusinessException e) {
            e.printStackTrace();
        }
        return jsonResult;
    }


    @ApiOperation(value = "用户信息分页查询/全查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页查询中的的页码page。如果page和size都为0，则进行全查询",
                    paramType = "query"),
            @ApiImplicitParam(name = "size", value = "分页查询中的的页码size.如果page和size都为0，则进行全查询",
                    paramType = "query")
    })
    @PostMapping("/selectByPage")
    public JsonResult selectByPage(@RequestParam(value = "page") Integer page, @RequestParam(value = "size") Integer size) {
        JsonResult jsonResult = new JsonResult();
        try {
            List<User> users;
            if (page == 0 && size == 0) {
                users = userService.selectAll();
            } else {
                users = userService.selectByPage(page, size);
            }
            if (users != null) {
                jsonResult.setCode("1");
                jsonResult.setMsg("查询成功");
                jsonResult.setData(users);
            }
        } catch (BusinessException e) {
            jsonResult.setCode("0");
            jsonResult.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return jsonResult;
    }

    @ApiOperation(value = "用户注册发送验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "用户对象",
                    paramType = "body")
    })
    @PostMapping("/registerSendCode")
    public JsonResult registerSendCode(@RequestBody User user, HttpSession httpSession) {
        JsonResult jsonResult = new JsonResult();
        try {
            String phone = user.getPhone();
            User user1 = userService.selectByPhone(phone);
            if (user1 == null) {
                int v = (int) ((Math.random() * 9 + 1) * 10000);
                String s = AliMsm.sendMsg(phone, String.valueOf(v));
//                String s = "OK";
                if ("OK".equals(s)) {
                    System.out.println("发送成功，验证码为：" + v);
                    /*存写验证码到session中*/
                    httpSession.setAttribute("code", v);
                    httpSession.setAttribute("user", user);
                    httpSession.setMaxInactiveInterval(50);
                    jsonResult.setCode("1");
                    jsonResult.setData(v);
                    jsonResult.setMsg("短信已发送，验证码有效时间为五十秒钟");
                } else {
                    throw new BusinessException("验证码发送失败，请联系管理员进行处理");
                }
            } else {
                jsonResult.setCode("0");
                jsonResult.setMsg("电话号码已注册。请登录");
            }
        } catch (Exception e) {
            jsonResult.setCode("0");
            jsonResult.setMsg("发生错误，请联系管理员");
            e.printStackTrace();
        }
        return jsonResult;
    }

    @ApiOperation(value = "用户登录发送验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "用户手机号",
                    paramType = "query")
    })
    @PostMapping("/loginSendCode")
    public JsonResult loginSendCode(@RequestParam(value = "phone") String phone,
                                    HttpSession httpSession) {
        JsonResult jsonResult = new JsonResult();
        try {
            User user = userService.selectByPhone(phone);
            System.out.println(user);
            if (user != null) {
                int v = (int) ((Math.random() * 9 + 1) * 10000);

                String s = AliMsm.sendMsg(phone, String.valueOf(v));
//                String s = "OK";
                if ("OK".equals(s)) {
                    System.out.println("发送成功，验证码为：" + v);
                    System.out.println(httpSession.getId());
                    /*存写验证码到session中*/
                    httpSession.setAttribute("code", v);
                    httpSession.setAttribute("phone", phone);
                    httpSession.setMaxInactiveInterval(500);
                    jsonResult.setCode("1");
                    jsonResult.setData(v);
                    jsonResult.setMsg("短信已发送，验证码有效时间为五十秒钟");
                } else {
                    throw new BusinessException("验证码发送失败，请联系管理员进行处理");
                }
            } else {
                jsonResult.setCode("0");
                jsonResult.setMsg("此电话未注册。请前往注册");
            }
        } catch (Exception e) {
            jsonResult.setCode("0");
            jsonResult.setMsg("发生错误，请联系管理员");
            e.printStackTrace();
        }
        return jsonResult;
    }

    @ApiOperation(value = "用户登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "用户验证码",
                    paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "用户手机号",
                    paramType = "query")
    })
    @PostMapping("/userLogin")
    public JsonResult userLogin(@RequestParam(value = "code") Integer code,
                                @RequestParam(value = "phone") String phone,
                                HttpSession httpSession) {
        JsonResult jsonResult = new JsonResult();
        Integer code1 = (Integer) httpSession.getAttribute("code");
        String phone1 = (String) httpSession.getAttribute("phone");
        if (code1 != null && code.equals(code1) && phone1.equals(phone)) {
            try {
                User user = userService.selectByPhone(phone);
                Date date = new Date();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
                Timestamp format = Timestamp.valueOf(simpleDateFormat.format(date));
                user.setLastAcTime(format);

                Integer id = user.getId();
                userService.updateLastAcTime(id, format);
                jsonResult.setCode("1");
                jsonResult.setMsg("登录成功");
                jsonResult.setData(user);
                httpSession.removeAttribute("code");
                httpSession.removeAttribute("phone");
            } catch (BusinessException e) {
                e.printStackTrace();
            }
        } else {
            jsonResult.setCode("0");
            jsonResult.setMsg("请获取验证码");
        }
        return jsonResult;
    }

    @ApiOperation(value = "用户注册")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "code", value = "json格式的验证码",
                    paramType = "query")
    )
    @PostMapping("/userRegister")
    public JsonResult userRegister(@RequestParam(value = "code") Integer code,
                                   HttpSession httpSession) {
        JsonResult jsonResult = new JsonResult();
        Integer code1 = (Integer) httpSession.getAttribute("code");
        User user = (User) httpSession.getAttribute("user");
        if (code1 != null && user != null) {
            if (code1.equals(code)) {
                try {
                    Integer register = userService.register(user);
                    if (register != null) {
                        jsonResult.setCode("1");
                        jsonResult.setData(user);
                        jsonResult.setMsg("注册成功,进入程序");
                        httpSession.removeAttribute("code");
                        httpSession.removeAttribute("user");
                    }
                } catch (BusinessException e) {
                    jsonResult.setCode("0");
                    jsonResult.setMsg(e.getMessage());
                    httpSession.removeAttribute("code");
                    httpSession.removeAttribute("user");
                    e.printStackTrace();
                }
            } else {
                jsonResult.setCode("0");
                jsonResult.setMsg("验证码有误，请重新获取验证码");
                httpSession.removeAttribute("code");
                httpSession.removeAttribute("user");
            }
        } else {
            jsonResult.setCode("0");
            jsonResult.setMsg("请获取验证码");
        }
        return jsonResult;
    }


    @PostMapping("/selectByMany")
    @ApiOperation(value = "此方法前端传入一个map map包含nameOrPhone（nameOrPhone是模糊查询部分内容），status(布尔类型)，\n" +
            "stationName必填项")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "map", value = "json字符串格式的map", paramType = "body")
    )
    public JsonResult selectByMany(@RequestBody Map<String, Object> map) {
        JsonResult jsonResult = new JsonResult();
        try {
            List<User> users = new ArrayList<User>();

            if (map.get("stationName") != null && map.get("stationName") != "") {
                List<Integer> integers = userService.selectStationName(map.get("stationName").toString());
                if (integers != null) {
                    for (Integer userId : integers) {
                        map.put("userId", userId);
                        List<User> userList = userService.selectByMany(map);
                        for (User user : userList) {
                            users.add(user);
                        }
                    }
                }
            } else {
                users = userService.selectByMany(map);
            }
            if(!users.isEmpty()){
                jsonResult.setCode("1");
                jsonResult.setMsg("查询成功");
                jsonResult.setData(users);
            }
        } catch (BusinessException e) {
            System.out.println(123);
            jsonResult.setCode("o");
            jsonResult.setMsg(e.getMessage());
        }
        return jsonResult;

    }

    @ApiOperation(value = "用户冻结或解冻")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "json格式的用户对象的id",
                    paramType = "query"),
            @ApiImplicitParam(name = "status", value = "json格式的用户对象status",
                    paramType = "query")
    })
    @PostMapping("/changeStatus")
    public JsonResult userChangeStatus(@RequestParam(value = "id") Integer id,
                                       @RequestParam(value = "status") Boolean status) {
        JsonResult jsonResult = new JsonResult();
        try {
            Integer integer = userService.changeStatus(id, status);
            if (integer != 0) {
                jsonResult.setCode("1");
                jsonResult.setMsg("状态更改成功");
            }
        } catch (BusinessException e) {
            jsonResult.setCode("0");
            jsonResult.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return jsonResult;
    }


    @ApiOperation(value = "查看用户信息的详情")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "id", value = "json格式的用户id",
                    paramType = "query")
    )
    @PostMapping("/checkUserInfo")
    public JsonResult checkUserInfo(@RequestParam(value = "id") Integer id,
                                    @RequestParam(value = "page")Integer page) {
        JsonResult jsonResult = new JsonResult();
        try {
            User user = userService.selectById(id);
            user.setListStations(null);
            List<UserAddress> userAddresses = userAddressService.selectByUserId(id);
            List<UODSVo> uodsVoList = uodsVoService.selectByUserIdAndPage(id,page);
            if (user != null && userAddresses != null && uodsVoList != null) {
                jsonResult.setCode("1");
                jsonResult.setMsg("用户收件信息及订单信息已查到，请查看");
                jsonResult.setValue("user", user);
                jsonResult.setValue("userAddresses", userAddresses);
                jsonResult.setValue("uodsVoList", uodsVoList);
            } else if (user != null && uodsVoList != null && userAddresses == null) {
                jsonResult.setCode("1");
                jsonResult.setMsg("用户信息与用户订单信息已查到，此用户无收货地址信息");
                jsonResult.setValue("user", user);
                jsonResult.setValue("uodsVoList", uodsVoList);
            } else if (user != null && uodsVoList == null && userAddresses != null) {
                jsonResult.setCode("1");
                jsonResult.setMsg("用户信息与用户收货地址信息已查到，此用户无订单信息");
                jsonResult.setValue("user", user);
                jsonResult.setValue("userAddresses", userAddresses);
            } else if (user != null && userAddresses == null && uodsVoList == null) {
                jsonResult.setCode("1");
                jsonResult.setMsg("无用户收货地址信息以及订单信息");
                jsonResult.setValue("user", user);
            }
        } catch (BusinessException e) {
            jsonResult.setCode("0");
            jsonResult.setMsg("查询失败，请联系管理员");
            e.printStackTrace();
        }
        return jsonResult;
    }


    @ApiOperation(value = "用户信息导出")
    @PostMapping("/exportUserInfo")
    public JsonResult exportUserInfo(HttpServletResponse response) {
        JsonResult jsonResult = new JsonResult();
        try {
            List<UODSVo> list = uodsVoService.selectAll();
            if (list != null) {
                ExcelUtil<UODSVo> util = new ExcelUtil<UODSVo>(UODSVo.class);
                util.exportExcel(response, list, "UserOrder");
                jsonResult.setCode("1");
                jsonResult.setMsg("导出成功");
            }

        } catch (Exception e) {
            jsonResult.setCode("0");
            jsonResult.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return jsonResult;
    }
}